import axios from 'axios';
import EventEmitter from './event';
import Cookies from 'js-cookie';

interface Params extends Object {
  customUrl?: string;
  customMethod?: 'POST' | 'GET';
}

class CallAPI {
  getOption = (actionName: string, params: Params = {}) => {
    // 支持无 nginx 访问
    const hostname = window.location.hostname;
    let prefix = window.urlPrefix;
    if (hostname === '127.0.0.1' || hostname === 'localhost') {
      prefix = '';
    }
    const url = params.customUrl ? `${params.customUrl}?ts=${Date.now()}` : `${prefix}/apis.json?actionName=${actionName}&ts=${Date.now()}`;

    const options = {
      url,
      method: params.customMethod || 'POST',
      type: 'json',
      data: JSON.stringify(params),
      headers: {
        'Content-Type': 'application/json',
      },
    };

    const csrfToken = Cookies.get('csrfToken');
    if (csrfToken) {
      options.headers['x-csrf-token'] = csrfToken;
    }

    return options;
  };

  dispatch = (actionName: string, params: Params) => {
    EventEmitter.emit('http.request', {
      actionName,
    });

    const options = this.getOption(actionName, params);

    return new Promise((resolve, reject) => {
      axios(options)
        .then((result) => {
          if (result.status === 200) {
            EventEmitter.emit('http.success', {
              actionName,
            });
            resolve(result.data);
          } else {
            EventEmitter.emit('http.fail', {
              actionName,
              message: result.data.message,
              statusCode: result.data.error_code || result.data.statusCode,
            });
            reject(result.data);
          }
        })
        .catch((error) => {
          EventEmitter.emit('http.fail', {
            actionName,
            message: error.response ? error.response.data.message : '网络异常，请稍后重试',
            statusCode: error.response ? error.response.data.error_code || error.response.data.statusCode : 500,
          });
          reject(error);
        });
    });
  };
}

const callAPI = new CallAPI();

export default callAPI.dispatch.bind(callAPI);
